package com.lrd.snapshotorder.util;

import com.lrd.snapshotorder.entity.SnapshotOrder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExportToExcel {

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private Integer serialNumber = 0;
    private Workbook workbook;
    private Sheet sheet;
    private OutputStream outputStream;

    public ExportToExcel(Workbook workbook, Sheet sheet, OutputStream outputStream) {
        this.workbook = workbook;
        this.sheet = sheet;
        this.outputStream = outputStream;
    }

    public <T> int exportToExcel(List<T> dataList, Map<String, String> headersMap, int startRow) throws IOException {

        int rowNum = startRow;

        // Write data to Excel
        for (T data : dataList) {
            Row row = sheet.createRow(rowNum++);
            int cellNum = 0;
            for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                Cell cell = row.createCell(cellNum++);
                String propertyName = entry.getValue();
                String propertyValue = getProperty(data, propertyName);
                cell.setCellValue(propertyValue);
            }
        }

        // Save and close the workbook
        workbook.write(outputStream);
        System.out.println("Excel file updated successfully!");

        // Return the next row number
        return rowNum;
    }

    private <T> String getProperty(T obj, String propertyName) {
        //序号一列从1自增
        if (propertyName == null) {
            serialNumber++;
            return serialNumber.toString();
        }
        try {
            Method method = obj.getClass().getMethod(propertyName);
            Object value = method.invoke(obj);
            if (value instanceof Date) {
                value = dateFormat.format(value);
            }
            return value != null ? value.toString() : "";
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void main(String[] args) throws Exception {

        // Specify the file name
        String fileName = "C:\\Users\\54461\\Desktop\\output.xlsx";
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        FileOutputStream outputStream = new FileOutputStream(fileName);
        /*try {
            workbook = WorkbookFactory.create(new FileOutputStream(fileName, true));
            sheet = workbook.getSheetAt(0);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        ExportToExcel exportToExcel = new ExportToExcel(workbook, sheet, outputStream);

        // Assuming you have a List of Order objects
        List<SnapshotOrder> orderList = new ArrayList<>();
        SnapshotOrder order = new SnapshotOrder();
        order.setOrderNo("234567890");
        order.setPostTime(new Date());
        order.setSender("zhangsan");
        order.setSenderAddress("zhangsanjia");
        order.setPostage(5);
        order.setWeight(1000);
        order.setRecipient("lisi");
        order.setRecipientAddress("lisijia");
        order.setId(1L);
        orderList.add(order);

        // Assuming you have the headersMap
        Map<String, String> headersMap = new LinkedHashMap<>();
        headersMap.put("序号（必填）", "id");
        headersMap.put("邮件号/订单号（必填）", "orderNo");
        headersMap.put("客户交寄时间（必填）", "postTime");
        headersMap.put("寄件人姓名", "sender");
        headersMap.put("寄件人地址", "senderAddress");
        headersMap.put("收件人姓名", "recipient");
        headersMap.put("收件人地址", "recipientAddress");
        headersMap.put("邮费（必填）", "postage");
        headersMap.put("重量（克）", "weight");
        headersMap.put("备注", "remarks");

        int cellNum = 0;
        Row row = sheet.createRow(0);
        for (Map.Entry<String, String> entry : headersMap.entrySet()) {
            Cell cell = row.createCell(cellNum++);
            cell.setCellValue(entry.getKey());
        }

        // Specify the starting row (e.g., 1 if you want to append after the header row)
        int startRow = 1;

        // Export to Excel and get the next starting row
        for (int i = 0; i < 2; i++) {
            startRow = exportToExcel.exportToExcel(orderList, headersMap, startRow);
        }

        outputStream.close();
        workbook.close();
        // If you have more pages of data, repeat the process with the updated startRow
        // startRow = exportToExcel(nextPageOfData, headersMap, fileName, startRow);
    }
}

